package repeater

import (
	"../common"
	"github.com/vmihailenco/msgpack"
)

type DataSet map[ReportMetric]Value

func joinDataSet(ds []DataSet) (ret DataSet) {
	ret = make(map[ReportMetric]Value)
	for _, d := range ds {
		for k, v := range d {
			if _, ok := ret[k]; !ok {
				ret[k] = v
			} else {
				ret[k] = append(ret[k], v...)
			}
		}
	}
	return
}
func (d DataSet) size() (i int64) {
	for _, x := range d {
		i += int64(len(x))
	}
	return
}
func (d DataSet) Add(rm ReportMetric, v float64) {
	d[rm] = append(d[rm], v)
}
func (cv DataSet) toBytes() (content []byte, err error) {
	content, err = msgpack.Marshal(&cv)
	return
}
func loadDataSet(content []byte) (cv DataSet, err error) {
	err = msgpack.Unmarshal(content, &cv)
	return
}

type Value []float64

func parse(dp *common.DataPoint) (day int, ip string, rm ReportMetric, v float64) {
	ret := common.Extract(dp.Name)
	ip = ret["ip"]
	day = common.DayInt(dp.Time)
	rm = ReportMetric{
		Head: ret["head"],
		Sub:  ret["sub"],
		Path: ret["path"],
	}
	v = dp.Val
	return
}

type ReportMetric struct {
	Head string `json:"h"`
	Sub  string `json:"s"`
	Path string `json:"p"`
}

func (r ReportMetric) valid() bool {
	return r.Head != "" && r.Sub != ""
}
func (r ReportMetric) toByte() []byte {
	content, err := msgpack.Marshal(&r)
	if err != nil {
		return nil
	}
	return content
}
